/**
 * 客户端数据服务
 * 通过 API 路由获取数据，避免直接访问 MongoDB
 */

export interface RealTimeData {
  timestamp: Date
  hospital: any | null
  alerts: any[]
  patientFlow: any[]
  departments: any[]
  equipment: any[]
  kpis: {
    bedUtilization: any | null
    patientFlow: any | null
    equipmentEfficiency: any | null
    patientSatisfaction: any | null
    emergencyResponse: any | null
    averageWaitTime: any | null
  }
}

class ClientDataService {
  private baseUrl = '/api/data'

  /**
   * 获取所有实时数据
   */
  async getAllRealTimeData(): Promise<RealTimeData> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取数据失败')
      }

      return result.data
    } catch (error) {
      console.error('从 API 获取数据失败:', error)
      throw error
    }
  }

  /**
   * 获取医院信息
   */
  async getHospitalInfo(): Promise<any | null> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'getHospital' }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取医院信息失败')
      }

      return result.data
    } catch (error) {
      console.error('获取医院信息失败:', error)
      throw error
    }
  }

  /**
   * 获取科室数据
   */
  async getDepartments(): Promise<any[]> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'getDepartments' }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取科室数据失败')
      }

      return result.data
    } catch (error) {
      console.error('获取科室数据失败:', error)
      throw error
    }
  }

  /**
   * 获取设备数据
   */
  async getEquipment(): Promise<any[]> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'getEquipment' }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取设备数据失败')
      }

      return result.data
    } catch (error) {
      console.error('获取设备数据失败:', error)
      throw error
    }
  }

  /**
   * 获取告警数据
   */
  async getAlerts(): Promise<any[]> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'getAlerts' }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取告警数据失败')
      }

      return result.data
    } catch (error) {
      console.error('获取告警数据失败:', error)
      throw error
    }
  }

  /**
   * 获取患者流量数据
   */
  async getPatientFlow(date?: Date): Promise<any[]> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'getPatientFlow',
          date: date?.toISOString()
        }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取患者流量数据失败')
      }

      return result.data
    } catch (error) {
      console.error('获取患者流量数据失败:', error)
      throw error
    }
  }

  /**
   * 获取KPI数据
   */
  async getKPIs(): Promise<any[]> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'getKPIs' }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取KPI数据失败')
      }

      return result.data
    } catch (error) {
      console.error('获取KPI数据失败:', error)
      throw error
    }
  }

  /**
   * 获取POI数据
   */
  async getPOIs(): Promise<any[]> {
    try {
      const response = await fetch(this.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ action: 'getPOIs' }),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || '获取POI数据失败')
      }

      return result.data
    } catch (error) {
      console.error('获取POI数据失败:', error)
      throw error
    }
  }

  /**
   * 订阅实时更新
   */
  subscribeToUpdates(callback: (data: RealTimeData) => void, interval: number = 10000): () => void {
    const intervalId = setInterval(async () => {
      try {
        const data = await this.getAllRealTimeData()
        callback(data)
      } catch (error) {
        console.error('实时数据更新失败:', error)
      }
    }, interval)

    // 立即执行一次
    this.getAllRealTimeData().then(callback).catch(console.error)

    return () => clearInterval(intervalId)
  }
}

// 创建全局实例
export const clientDataService = new ClientDataService()

export default clientDataService
